﻿using HandyControl.Themes;
using HandyControl.Tools;
using Mapster;
using Newtonsoft.Json;
using SqlSugar;
using System.IO;
using System.Windows;
using YY.Admin.Core;
using YY.Admin.Core.Const;
using YY.Admin.Core.EventBus;
using YY.Admin.Core.Helper;
using YY.Admin.Core.Model;
using YY.Admin.Core.Session;
using HcSkinType = HandyControl.Data.SkinType;

namespace YY.Admin.ViewModels
{
    /// <summary>
    /// 系统设置
    /// </summary>
    public class AppSettingsViewModel : BindableBase
    {
        /// <summary>
        /// 皮肤类型
        /// </summary>
        private HcSkinType? _skinType;
        public HcSkinType? SkinType
        {
            get => _skinType ??= GetDefaultSkinType();
            set
            {
                if (SetProperty(ref _skinType, value) && value != null)
                {
                    if (!SyncWithSystem)
                    {
                        UpdateSkin(value.Value);
                        UpdateAppSettings();
                    }
                }
            }
        }

        /// <summary>
        /// 皮肤是否与系统同步
        /// </summary>
        private bool _syncWithSystem;
        public bool SyncWithSystem
        {
            get => _syncWithSystem;
            set
            {
                if (SetProperty(ref _syncWithSystem, value))
                {
                    RaisePropertyChanged(nameof(IsNotSyncWithSystem));
                    if (value)
                    {
                        SkinType = GetSkinTypeBySystem();
                        UpdateSkin(SkinType.Value);
                    }
                    UpdateAppSettings();
                }
            }
        }

        public bool IsNotSyncWithSystem => !SyncWithSystem;

        /// <summary>
        /// 是否显示TabControl
        /// </summary>
        private bool _isTabControlVisible = true;

        public bool IsTabControlVisible
        {
            get => _isTabControlVisible;
            set {
                if (SetProperty(ref _isTabControlVisible, value))
                {
                    UpdateAppSettings();
                }
            }
        }

        /// <summary>
        /// 获取默认皮肤类型
        /// </summary>
        /// <returns></returns>
        private HcSkinType GetDefaultSkinType()
        {
            return SyncWithSystem ? GetSkinTypeBySystem() : (HcSkinType)Properties.AppSettings.Default.SkinType;
        }

        /// <summary>
        /// 根据系统主题配置获取对应皮肤类型
        /// </summary>
        /// <returns></returns>
        public static HcSkinType GetSkinTypeBySystem()
        {
            return SystemHelper.DetermineIfInLightThemeMode()
                    ? HcSkinType.Default
                    : HcSkinType.Dark;
        }

        /// <summary>
        /// 从ResourceDictionary中获取皮肤类型
        /// </summary>
        /// <returns></returns>
        public static HcSkinType GetSkinType()
        {
            var _theme = Application.Current.Resources.MergedDictionaries.OfType<Theme>().FirstOrDefault();
            if (_theme != null)
            {
                return _theme?.Skin ?? HcSkinType.Default;
            }
            var skin = Application.Current.Resources.MergedDictionaries
                .Where(it => it.Source.OriginalString.StartsWith("pack://application:,,,/HandyControl;component/Themes/Skin"))
                .FirstOrDefault();
            if (skin != null)
            {
                string OriginalString = skin.Source.OriginalString;
                // 4：Skin的长度
                int skinStart = OriginalString.IndexOf("Skin") + 4;
                int dotIndex = OriginalString.LastIndexOf('.');
                string skinName = OriginalString.Substring(skinStart, dotIndex - skinStart);
                return (HcSkinType)Enum.Parse(typeof(HcSkinType), skinName);
            }
            return HcSkinType.Default;
        }

        /// <summary>
        /// 更新皮肤
        /// </summary>
        /// <param name="skinType"></param>
        public static void UpdateSkin(HcSkinType skinType)
        {
            // 配置方式：<hc:Theme />
            var theme = Application.Current.Resources.MergedDictionaries.OfType<Theme>().FirstOrDefault();
            if (theme != null)
            {
                //theme.Skin = skin;
                theme.MergedDictionaries[0].Source = ResourceHelper.GetSkin(skinType).Source;
                theme.MergedDictionaries[1].Source = ResourceHelper.GetStandaloneTheme().Source;
                AddResourceDictionary(skinType);
                return;
            }

            // 配置方式：<ResourceDictionary />
            var skins = Application.Current.Resources.MergedDictionaries
                .Where(it => it.Source.OriginalString.StartsWith("pack://application:,,,/HandyControl;component/Themes/"))
                .ToList();
            if (skins == null || skins.Count < 2)
            {
                return;
            }
            skins[0].Source = ResourceHelper.GetSkin(skinType).Source;
            skins[1].Source = ResourceHelper.GetStandaloneTheme().Source;

            // 添加除HandyControl之外的资源字典
            AddResourceDictionary(skinType);
            
            ContainerLocator.Container.Resolve<IEventAggregator>().GetEvent<ThemeChangedEvent>().Publish(skinType);
        }

        /// <summary>
        /// 获取文件完整路径
        /// </summary>
        /// <returns></returns>
        public static string GetFilePath()
        {
            string filePathSuffix = string.Format(CommonConst.AppSettingsFilePath, AppSession.CurrentUser!.Account);
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePathSuffix);
        }

        /// <summary>
        /// 更新系统设置
        /// 默认配置由MainWindowViewModel保存
        /// </summary>
        /// <param name="appSettingsViewModel">系统设置VM</param>
        public void UpdateAppSettings()
        {
            var filePath = GetFilePath();
            if (!File.Exists(filePath))
            {
                return;
            }
            SaveAppSettings(filePath);
        }

        /// <summary>
        /// 保存系统设置
        /// </summary>
        /// <param name="filePath"></param>
        public void SaveAppSettings(string? filePath = null)
        {
            filePath ??= GetFilePath();
            var directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory!);
            }
            var appSettings = this.Adapt<AppSettings>();
            var json = JsonConvert.SerializeObject(appSettings, Formatting.Indented);
            // 保存到文件
            File.WriteAllText(filePath, json);
        }

        /// <summary>
        /// 添加资源字典
        /// </summary>
        /// <param name="skinType"></param>
        private static void AddResourceDictionary(HcSkinType skinType)
        {
            // 先移除上一次主题添加的资源字典，否则会影响当前主题
            RemoveResourceDictionaryBySource("/Resources/Styles/HandyControl/Colors.xaml");
            RemoveResourceDictionaryBySource("/Resources/Styles/HandyControl/ColorsDark.xaml");
            RemoveResourceDictionaryBySource("/Resources/Styles/HandyControl/ColorsViolet.xaml");
            RemoveResourceDictionaryBySource("/Resources/Styles/HandyControl/Brushes.xaml");
            if (skinType == HcSkinType.Default)
            {
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("/Resources/Styles/HandyControl/Colors.xaml", UriKind.Relative)
                });
            } else if (skinType == HcSkinType.Dark)
            {
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("/Resources/Styles/HandyControl/ColorsDark.xaml", UriKind.Relative)
                });
            } else if (skinType == HcSkinType.Violet)
            {
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("/Resources/Styles/HandyControl/ColorsViolet.xaml", UriKind.Relative)
                });
            }
            Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
            {
                Source = new Uri("/Resources/Styles/HandyControl/Brushes.xaml", UriKind.Relative)
            });
        }

        /// <summary>
        /// 移除资源字典
        /// </summary>
        /// <param name="sourceEndsWith"></param>
        private static void RemoveResourceDictionaryBySource(string sourceEndsWith)
        {
            var dictToRemove = Application.Current.Resources.MergedDictionaries
                .FirstOrDefault(d => d.Source?.OriginalString?.EndsWith(sourceEndsWith) == true);

            if (dictToRemove != null)
            {
                Application.Current.Resources.MergedDictionaries.Remove(dictToRemove);
            }
        }
    }
}
